package com.jmb.waimao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jmb.waimao.entity.EmailAddress;
import com.jmb.waimao.mapper.EmailAddressMapper;
import com.jmb.waimao.service.EmailAddressService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * Implementation of EmailAddressService
 */
@Service
@Slf4j
public class EmailAddressServiceImpl extends ServiceImpl<EmailAddressMapper, EmailAddress> implements EmailAddressService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int importFromCsv(MultipartFile file, String groupName) {
        int successCount = 0;
        
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(file.getInputStream()));
             CSVParser csvParser = new CSVParser(reader, CSVFormat.DEFAULT.withFirstRecordAsHeader())) {
            
            List<EmailAddress> emailAddresses = new ArrayList<>();
            
            for (CSVRecord record : csvParser) {
                String email = record.get("email");
                String name = record.getRecordNumber() < record.size() ? record.get("name") : null;
                
                EmailAddress emailAddress = new EmailAddress();
                emailAddress.setEmail(email);
                emailAddress.setName(name);
                emailAddress.setGroupName(groupName);
                emailAddress.setCreateTime(LocalDateTime.now());
                emailAddress.setUpdateTime(LocalDateTime.now());
                emailAddress.setDeleted(0);
                
                emailAddresses.add(emailAddress);
                
                // Save in batches of 100
                if (emailAddresses.size() >= 100) {
                    saveBatch(emailAddresses);
                    successCount += emailAddresses.size();
                    emailAddresses.clear();
                }
            }
            
            // Save remaining records
            if (!emailAddresses.isEmpty()) {
                saveBatch(emailAddresses);
                successCount += emailAddresses.size();
            }
            
        } catch (Exception e) {
            log.error("Error importing email addresses from CSV", e);
            throw new RuntimeException("Failed to import email addresses: " + e.getMessage());
        }
        
        return successCount;
    }

    @Override
    public List<EmailAddress> getByGroup(String groupName) {
        LambdaQueryWrapper<EmailAddress> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(EmailAddress::getGroupName, groupName)
                    .eq(EmailAddress::getDeleted, 0);
        return list(queryWrapper);
    }
}
